package com.example.lib_base.mvvm

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.lib_base.Res
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.text.SimpleDateFormat

open class BaseViewModel:ViewModel() {

    fun <T> httpRequest(s:suspend ()-> Res<T>, success:(T)->Unit){
        viewModelScope.launch {
            try {
                val invoke = s.invoke()
                if (invoke.code == 200){
                    success(invoke.data)
                }else{
                    Log.i("sss",invoke.message)
                }
            }catch (e:Exception){
                Log.i("sss",e.message.toString())
            }
        }
    }


    fun <T> roomRequest(s:suspend ()->T, success:(T)->Unit){
        viewModelScope.launch {
            try {
                val invoke = s.invoke()
                if (invoke != null){
                    success(invoke)
                }else{
                    Log.i("sss","操作不正常")
                }
            }catch (e:Exception){
                Log.i("sss",e.message.toString())
            }
        }
    }


    fun <T> httpRequest2(s:suspend ()-> T, success:(T)->Unit){
        viewModelScope.launch {
            try {
                val invoke = s.invoke()
                success(invoke)
            }catch (e:Exception){
                Log.i("sss",e.message.toString())
            }
        }
    }


    fun mapToBody(any: Any):RequestBody{
       return RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),Gson().toJson(any))
    }

    fun getDateTimeString(time:Long):String{
        return SimpleDateFormat("yyyyMMddHHmmss").format(time)
    }

    fun getDateTime(time:Long):String{
        return SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)
    }

    fun getTime(time:Long):String{
        return SimpleDateFormat("HH:mm:ss").format(time)
    }

    fun getDate(time:Long):String{
        return SimpleDateFormat("yyyy-MM-dd").format(time)
    }

    fun getMonth():String{
        return SimpleDateFormat("MM").format(System.currentTimeMillis())
    }

    fun getYear():String{
        return SimpleDateFormat("yyyy").format(System.currentTimeMillis())
    }



}